package com.kent.hellokotlin.bBasic

import com.kent.hellokotlin.aStart.parseInt

fun main() {

}

//If 表达式
fun fooIf() {
    val a = 1
    val b = (Math.random() * 10).toInt()
    var max = a
    if (a < b) {
        max = b
    }
    //
    max = if (a > b) a else b
    //
    max = if (a > b) {
        println("choose a")
        a
    } else {
        println("choose b")
        b
    }
}

//When 表达式
fun fooWhen() {
    val x = (Math.random() * 10).toInt()
    when (x) {
        0 -> println("x == 0")
        1 -> println("x == 1")
        2 -> println("x == 2")
        3, 4, 5 -> println("x is 3 or 4 or 5")
        else -> println("x is more then 5")
    }

    val xStr = "" + x

    when (x) {
        parseInt(xStr) -> println("xStr encodes x")
        else -> println("s does not encode x")
    }


    val validNumbers = Array(20) { i: Int -> i }
    val validNumbers1 = Array(10) { it }
    when (x) {
        in 1..10 -> println("x is in 1..10")
        in validNumbers -> println("x is valid")
        !in 20..30 -> println("x is out of the range")
        else -> println("none of above")
    }

    fun Int.isOdd() = this % 2 == 1
    fun Int.isEven() = this % 2 == 0

    when {
        x.isOdd() -> println("x is odd")
        x.isEven() -> println("x is even")
        else -> println("x is funny")
    }

    val strWithSuffix = "error.log"
    val hasSuffix = hasSuffix(strWithSuffix, ".log")
}

fun hasSuffix(any: Any, suffix: String) = when (any) {
    is String -> any.endsWith(suffix)
    else -> false
}

//For 循环
fun fooFor() {
    for (i in 1..3) {
        println(i)
    }
    for (i in 6 downTo 0 step 2) {
        println(i)
    }

    val array = Array(5) { i: Int -> (i * i).toString() }

    for (i in array) {
        println(i)
    }
    for (i in array.indices) {
        println(array[i])
    }
    val withIndex: Iterable<IndexedValue<String>> = array.withIndex()
    for ((index, value) in withIndex) {
        println("the element at $index is $value")
    }

    //While 循环
    fun fooWhile() {
        var x: Int = 10
        while (x > 0) {
            x--
        }

        do {
            val y = if (x > 0) 1 else null
        } while (y != null) // y 在此处可见
    }
}